package com.work.common.util;

import com.work.common.enums.AuthType;
import com.work.common.exp.WorkException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.ObjectUtils;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwsUtil {

    private static final Long DEFAULT_EXPIRE_TIME = 1000 * 60 * 60 * 24 * 7L;

    private static final SecretKey secretKey;

    static {
        secretKey = Jwts.SIG.HS256.key().build();
    }

    public static String getToken(String params, Long expireTime) {
        return Jwts.builder()
                .subject(params)
                .signWith(secretKey)
                .expiration(new Date(System.currentTimeMillis() + ObjectUtils.defaultIfNull(expireTime, DEFAULT_EXPIRE_TIME)))
                .compact();
    }

    public static String getToken(String params) {
        return getToken(params, null);
    }

    public static String parseToken(String token) {
        try {
            return Jwts.parser()
                    .verifyWith(secretKey)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload()
                    .getSubject();
        } catch (ExpiredJwtException e) {
            final AuthType loginExpired = AuthType.LOGIN_EXPIRED;
            throw new WorkException(loginExpired.getCode(), loginExpired.getMsg());
        }
    }
}
